﻿using System.Collections.Generic;
using System.Collections;
using System;
using EzyGoEzySystem.Models;
using EzyGoEzySystem.Interfaces;
using System.Linq;

namespace EzyGoEzySystem.Services 
{ 
    ///<summary>
    /// receive the list of TravelJournalEntries from TicketController to calculate the fare for each entry
    /// update the balance for customer
    ///</summary>
    ///<author> Trang</author>
    
    public class FareManagementServices : IFarePayment
    {   
        //public const double baseFare = 0.005; // 0.005 dollard for each second of travelling
        public double baseFare = 0;

        public FareManagementServices()
        {
            using (var dbContext = new EzyGoEzyDBContext())
            {
                var confs = from conf in dbContext.AdminConfigurations
                            select conf;
                baseFare = confs.First().BaseFare;
            }
        }

        /// <summary>
        ///  calculate fare for each entry then update its balance
        /// </summary>
        /// <param name="t"></param>
        private void ChargeCalculate(TravelJournalEntry t, EzyGoEzyDBContext dbContext)
        {
            DateTime boardTime = t.BoardTime;
            DateTime alightTime = (DateTime)t.AlightTime;// require explicit casting because AlightTime can get null value
            double travellingTime = alightTime.Subtract(boardTime).TotalSeconds;
            double travellingCharge = baseFare*travellingTime;

            //find the correct travel journal entry
            //var travelJournalEntries = from travelEntry in dbContext.TravelJournalEntries
            //                         where travelEntry.ID == t.ID
            //                         select travelEntry;

            //var travelJournalEntry = travelJournalEntries.First();

            /////update the fare property of TravelJournalEntry
            //travelJournalEntry.Fare = travellingCharge;

            /////deduct account of customer
            //travelJournalEntry.Account.Balance = t.Account.Balance - travellingCharge;

            //update the fare property of TravelJournalEntry
            t.Fare = Math.Round(travellingCharge, 2);

            //deduct account of customer
            t.Account.Balance = Math.Round(t.Account.Balance - travellingCharge, 2);

            // persist to db
            dbContext.SaveChanges();
        }

        public IEnumerable<TravelJournalEntry> ChargeCalculate(IEnumerable<TravelJournalEntry> entryList, EzyGoEzyDBContext dbContext)
        {
            
           
            foreach(TravelJournalEntry entry in entryList)
            {
              ChargeCalculate(entry, dbContext);
            }
            return entryList;
        }
    }
}